package com.rajesh.messageservice.helper;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;

/**
 * 服务中做循环任务的帮助类
 */
public class PollingUtils {

    /**
     * 启动循环服务
     *
     * @author Rajesh
     * @param context 服务所在上下文
     * @param seconds 循环时间间隔（秒）
     * @param cls 服务类
     * @param action 服务名
     * */
    public static void startService(Context context, int seconds, Class<?> cls, String action){
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, cls);
        intent.setAction(action);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        long triggerAtTime = SystemClock.elapsedRealtime();
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, seconds * 1000, pendingIntent);
    }

    /**
     * 取消服务循环
     *
     * @author Rajesh
     * @param context 服务所在上下文
     * @param cls 服务类
     * @param action 服务名
     * */
    public static void stopService(Context context, Class<?> cls, String action){
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, cls);
        intent.setAction(action);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.cancel(pendingIntent);
    }

}
